package com.changgou.goods.service.impl;

import com.changgou.goods.dao.CategoryMapper;
import com.changgou.goods.dao.ParaMapper;
import com.changgou.goods.dao.SpecMapper;
import com.changgou.goods.pojo.Category;
import com.changgou.goods.pojo.Para;
import com.changgou.goods.service.ParaService;
import com.changgou.goods.service.SpecService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class ParaServiceImpl implements ParaService {

    @Autowired
    private ParaMapper paraMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Para> findAll() {
        return paraMapper.selectAll();
    }

    @Override
    public void add(Para para) {
        paraMapper.insert(para);
    }

    @Override
    public List<Para> findList(Para para) {
        Example example = createExample(para);
        List<Para> paras = paraMapper.selectByExample(example);
        return paras;
    }

    @Override
    public PageInfo<Para> findPage(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        PageInfo<Para> pageInfo = new PageInfo<>(paraMapper.selectAll());
        return pageInfo;
    }

    @Override
    public PageInfo<Para> findPage(Integer page, Integer size, Para para) {
        Example example = createExample(para);
        PageHelper.startPage(page, size);
        PageInfo<Para> pageInfo = new PageInfo<>(paraMapper.selectByExample(example));
        return pageInfo;
    }

    @Override
    public List<Para> findByCategoryId(Integer id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        Para para = new Para();
        para.setTemplateId(category.getTemplateId());
        return paraMapper.select(para);
    }

    @Override
    public Para findById(Integer id) {
        return paraMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Para para) {
        paraMapper.updateByPrimaryKey(para);
    }

    @Override
    public void delete(Integer id) {
        paraMapper.deleteByPrimaryKey(id);
    }

    /****
     * 构建查询对象
     * @param para
     * @return
     */
    private Example createExample(Para para) {
        Example example = new Example(Para.class);
        Example.Criteria criteria = example.createCriteria();
        if (para != null) {
            if (StringUtils.isNotEmpty(para.getName())) {
                criteria.andLike("name", "%" + para.getName() + "%");
            }
            if (StringUtils.isNotEmpty(para.getOptions())) {
                criteria.andEqualTo("options", para.getOptions());
            }
        }
        return example;
    }
}
